package com.mall.dao;

import com.mall.domain.Page;
import com.mall.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户的持久层接口
 *
 * @author : liangY
 * @date : 2020-12-25 19:35
 */
@Repository
public interface IUserDao {

    /**
     * 验证登录
     *
     * @param loginUser
     * @return
     */
    @Results(id = "loginMap",
            value = {
                    @Result(id = true, property = "id", column = "id"),
                    @Result(column = "id",
                            property = "role",
                            one = @One(select = "com.mall.dao.IRoleDao.findOne", fetchType = FetchType.LAZY))
            })
    @Select("select * from tb_user where username=#{loginUser.username} and password=#{loginUser.password} and status=1")
    User login(@Param("loginUser") User loginUser);

    /**
     * 查询所有用户
     *
     * @param page 分页实体类
     * @return
     */
    @Results(id = "userMap",
            value = {
                    @Result(id = true, property = "id", column = "id"),
                    @Result(column = "id",
                            property = "role",
                            one = @One(select = "com.mall.dao.IRoleDao.findOne", fetchType = FetchType.LAZY))
            })
    @Select("select * from tb_user where username like #{page.query} limit #{page.num},#{page.size}")
    List<User> findAll(@Param("page") Page page);

    /**
     * 查询所有用户数量
     *
     * @return
     */
    @Select("select count(*) from tb_user")
    Integer findTotal();

    /**
     * 更新用户
     *
     * @param user 会员实体类
     * @return
     */
    @Update("update tb_user set username=#{username},password=#{password}," +
            "tel=#{tel},file=#{file}," +
            "status=#{status},updated=#{updated} where id=#{id}")
    Integer update(User user);

    @Update("update tb_user set password=#{password},username=#{username},touxiang=#{touxiang} where id=#{id}")
    Integer update2(User user);

    /**
     * 添加用户
     *
     * @param user 用户实体类
     * @return
     */
    @Insert("insert into tb_user values(#{id},#{username},#{password},#{tel}," +
            "#{file},#{status},#{created},#{updated})")
    @SelectKey(keyColumn = "id", keyProperty = "id", resultType = Integer.class,
            before = false, statement = {"select last_insert_id()"})
    Integer add(User user);

    /**
     * 添加用户角色
     *
     * @param user_id
     * @return
     */
    @Insert("insert into tb_user_role values(default,#{user_id},2)")
    @SelectKey(keyColumn = "id", keyProperty = "id", resultType = Integer.class,
            before = false, statement = {"select last_insert_id()"})
    Integer addRole(@Param("user_id") Integer user_id);

    /**
     * 删除用户
     *
     * @param id 用户编号
     * @return
     */
    @Delete("delete from tb_user where id = #{id}")
    Integer del(Integer id);

}
